//
//  EventDetailVC.swift
//  Hyphenate-Demo-Swift
//
//  Created by cydida on 2018/12/2.
//  Copyright © 2018年 curtainups. All rights reserved.
//

import UIKit
import Hyphenate
import NVActivityIndicatorView

import SwiftEventBus
//import Toast_Swift
//import DVImageBrowserVC
//import SKPhoto
//import JXPhotoBrowser

class evaluateModel: NSObject {
    var timestatmp:String?
    var comment:String?
    var username:String?
}

class eventDetailModel: NSObject {
    var title:String?
    var type:String?
    var array:[String]?
    var evaluateArr:[evaluateModel]?
}

class EventDetailVC: UIViewController,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,NVActivityIndicatorViewable{

    @IBOutlet weak var timeIcon: UIImageView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var contentLabel: UILabel!
    var eid = ""
    @IBOutlet weak var timeStatusLabel: UILabel!
 
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var acceptBtn: UIButton!
    @IBOutlet weak var cancelBtn: UIButton!
    
    @IBOutlet weak var commentBtn: UIButton!
    @IBOutlet weak var heightCons: NSLayoutConstraint!
    
    @IBOutlet weak var imgBtn: UIButton!
    var hiddenFlag:Int8 = -1
    var strMessage = ""
    var groupId = ""
    var dataDic = Dictionary<Int, eventDetailModel>()
    
    lazy var imageList:[String] = Array()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        getEventById(eventId: eid)
    }
    
    override func updateViewConstraints() {
        super.updateViewConstraints()
        
        if imageList.count > 0 {
            
            heightCons.constant = 80
            
            let url = NSURL(string: imageList.first!)
            
            let str = imageList[0] as String
            
            self.imgBtn.setBackgroundImage(nil, for: .normal)
//            self.imgBtn?.sd_setBackgroundImageWithURL(with: url, for: .normal)
//            self.imgBtn?.sd_setBackgroundImage(with:url, for:.normal, placeholderImage: nil)
//            imgBtn?.sd_setBackgroundImageWithURL(with: url!, for: .normal)
//            imgBtn?.sd_setBackgroundImage(with: url, for: .normal)
            
            imgBtn.sd_setBackgroundImage(with: URL(string: self.imageList[0] as! String), for: .normal, placeholderImage: nil)
            imgBtn.setAttributedTitle(setShadowByText(text: imageList.count), for: .normal)

        }
        else
        {
            
        }
        
    }
    
    //设置文字阴影
    private func setShadowByText(text:Int)->NSAttributedString{
        
        let str = "+\(String(describing: text))"
        let shadow = NSShadow.init()
        shadow.shadowColor = UIColor.lightGray
        shadow.shadowOffset = CGSize.init(width: 1.5, height:1.5)
        let arributedText = NSAttributedString.init(string:str, attributes: [NSAttributedStringKey.foregroundColor:UIColor.white,  NSAttributedStringKey.font:UIFont.systemFont(ofSize:40), NSAttributedStringKey.shadow: shadow])
        
        return arributedText
    }
    
    // MARK:添加评论--弹框
    
    @IBAction func addEvaluateAction(_ sender: Any) {
        
        weak var weakSelf = self
        
        var inputText:UITextField = UITextField();
        let msgAlertCtr = UIAlertController.init(title: "comment", message: "", preferredStyle: .alert)
        let ok = UIAlertAction.init(title: "OK".localized(), style:.default) { (action:UIAlertAction) ->() in
            if((inputText.text) != ""){
//                print("你输入的是：\(String(describing: inputText.text))")
                
                weakSelf?.addEvaluateEvent(comment: (String(describing: inputText.text!)))
            }
//            else{
//
//            }
        }
        
        let cancel = UIAlertAction.init(title: "Cancel".localized(), style:.cancel) { (action:UIAlertAction) -> ()in
//            print("取消输入")
        }
        
        msgAlertCtr.addAction(ok)
        msgAlertCtr.addAction(cancel)
        //添加textField输入框
        msgAlertCtr.addTextField { (textField) in
            //设置传入的textField为初始化UITextField
            inputText = textField
            inputText.placeholder = "please input your comment".localized()
        }
        //设置到当前视图
        self.present(msgAlertCtr, animated: true, completion: nil)
    }
    
    // MARK:添加评论--发送请求
    private func addEvaluateEvent(comment:String){
        
        startAnimating(message: "loading".localized())

        
        let  parameters = [
            "eventId" : eid,
            "comment" : comment,
            "username": EMClient.shared().currentUsername
            ]
        
        weak var weakSelf = self
        
        CUHTTP.instance().makePostData(url: "eventComment", parameters:parameters, success: { response in
            print(response?.response?.statusCode ?? "??")      //成功时，返回200
            weakSelf?.stopAnimating()
            if let code = response?.response?.statusCode  {
                if(code == 200)
                {
                    weakSelf?.show("Succeed".localized())
                  
                    
                    if(self.groupId != "")
                    {
                        let message = EMSDKHelper.createTextMessage(self.strMessage, to:self.groupId, EMChatTypeGroupChat, ["eventId": self.eid])
                        self._sendMessage(message: message)
                    }
                    else
                    {
                        self.dataDic.forEach({ (arg0) in
                            let (key, value) = arg0
                            value.array?.forEach({ (String) in
                                
                                if(String != EMClient.shared().currentUsername){
                                    let message = EMSDKHelper.createTextMessage(self.strMessage, to:String, EMChatTypeChat, ["eventId": self.eid])
                                    self._sendMessage(message: message)
                                }
                            })
                            
                        })
                        
                    }
                    
                    
                    
                    
                    
                    weakSelf?.backAction()
                }
                else
                {
                    weakSelf?.show("Failed".localized())
                }
            }
            
        }, failure: { response in
            // API call Failure
//            weakSelf?.stopAnimating()
            weakSelf?.show("Failed".localized())
        })
    
        
    }
    func getWeekDay(dayStr: String) -> String {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        let date = dateFormatter.date(from: dayStr)
        
        dateFormatter.dateFormat = "yyyy-MM-dd EEEE"
        
        let dateStr = dateFormatter.string(from: date!)
        
        //        var weekStr = dateStr.split(separator: " ")[1]
        
        return String(dateStr)
    }
    
    func _sendMessage(message: EMMessage) {
        DispatchQueue.global().async {
            EMClient.shared().chatManager.send(message, progress: nil) { (message, error) in
                DispatchQueue.main.async {
                    SwiftEventBus.post("addMessage", sender: message)
                }
            }
        }
    }
    
    @IBAction func imgBtnAction(_ sender: Any)
    {
//        DVImageBrowserVC
        let vc = DVImageBrowserVC()
        vc.images = self.imageList
        vc.index = 0
        vc.pageCurrentImg = UIImage(named: "pageCurrentImg")
        vc.pageNoramlImg = UIImage(named: "pageNoramlImg")
//        vc.delegate = self
        self.navigationController?.present(vc, animated: true)

    }
    
//    func numberOfPhotos(in photoBrowser: PhotoBrowser) -> Int {
//        return self.imageList.count
//    }
//
//    /// 各缩略图图片，也是图片加载完成前的 placeholder
//    func photoBrowser(_ photoBrowser: PhotoBrowser, thumbnailImageForIndex index: Int) -> UIImage? {
////        let cell = collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? MomentsPhotoCollectionViewCell
//        return UIImage()
//    }
////
    @IBAction func confrimAction(_ sender: Any)
    {
        postEventStatus(status: "going")
    }
    @IBAction func cancelAction(_ sender: Any)
    {
        postEventStatus(status: "notgoing")
    }
    private func getEventById(eventId : String) {
        timeIcon.isHidden = true
        startAnimating(message: "loading".localized())
        weak var weakSelf = self
        
        let urlstr = "event?eventId=" + eventId
        let cuHTTP = CUHTTP.instance()
        cuHTTP.makeGetData(url: urlstr, success: {response in
            print("Response String: \(String(describing: response?.result.value))")
            print(response?.response?.statusCode ?? "??")
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                var json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: Any]
                print(json ?? "??")
                
                weakSelf?.timeIcon.isHidden = false
                weakSelf?.timeStatusLabel.layer.borderWidth = 1.0
                weakSelf?.timeStatusLabel.layer.borderColor = UIColor.init(red: 0, green: 110/255.0, blue: 216/255.0, alpha: 1.0).cgColor
                
                
                weakSelf?.collectionView.contentInset = UIEdgeInsetsMake(0, 20, 0, 20)
                
                weakSelf?.collectionView.register(UINib.init(nibName: "CollectionReusableView", bundle: nil),forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "header")
//                weakSelf?.collectionView.register(EventDetailCollCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
//                weakSelf?.collectionView.register(EvaluateListCell.self, forCellWithReuseIdentifier: "evaluateListCell")
                
                if  json?["events"] is NSNull {
                    
                    weak var weakSelf = self
                    let alert = UIAlertController(title:"event Deleted".localized(),message:"",preferredStyle:UIAlertControllerStyle.alert)
                    let okAction = UIAlertAction(title:EnStatic.getWord(keyWord: "OK"),style:UIAlertActionStyle.default,handler:{(alerts:UIAlertAction) -> Void in
                        weakSelf?.navigationController?.popViewController(animated: true)
                    })
                    
                    alert.addAction(okAction);
                    
                    self.present(alert,animated: true,completion: nil)
                    return
                }
                
                if let loopE0 = json?["events"]
                {
                    if let loopE = (loopE0 as? [String: Any])
                    {
                        print(loopE)
                        
                        if let str_groupId = loopE["groupId"] {
                                if str_groupId is NSNull {
                                    
                                }else{
                                self.groupId = str_groupId as! String
                                    
                            }
                        }
                        guard let eventTitle = loopE["eventTitle"],
                              let eventType = loopE["eventType"],
                              let owner = loopE["owner"],
                              let description = loopE["description"],
                              let startTime = loopE["startTime"],
                              let calendarType = loopE["calendarType"],
                              let str_date = loopE["date"],
                              let endTime = loopE["endTime"] else {
                            return
                        }
                        
                        var creator = ""
//
                        if (calendarType as? String) == "private"
                        {
                            creator = ""
                        }
                        else
                        {
                            creator = EMUserProfileManager.sharedInstance.getNickNameWithUsername(username: String(describing: owner)) 
                        }
                        
                        var  time = "Creator:".localized() +  creator
                        
                        if(endTime as! String).count > 0 && (startTime as! String).count > 0
                        {
                            
                            self.strMessage = (eventTitle as! String)  + "\n\n" + self.getWeekDay(dayStr: str_date as! String)  + " \n " + CUTimeFormat.get12Time(time:startTime as! String) + " - " + CUTimeFormat.get12Time(time:endTime as! String)
                            time = CUTimeFormat.get12Time(time: startTime as! String) + "-" + CUTimeFormat.get12Time(time: endTime as! String) + " " + "Creator:".localized() +  creator
                        }else{
                             self.strMessage = (eventTitle as! String) + "\n\n" + self.getWeekDay(dayStr: str_date as! String)
                        }
                            
                   
                        
                        weakSelf?.titleLabel.text = eventTitle as? String
                        weakSelf?.contentLabel.text = description as? String
                        weakSelf?.timeLabel.text = time
                        
                        weakSelf?.timeStatusLabel.text = " " + EnStatic.getWord(keyWord: (eventType as! String)) + " "

                        if let going = loopE["going"] as? [String] {
                            
//                            let tmp = weakSelf?.getEventArray(eventStr: going)
                            let count = String(format: "%d", going.count)
                            let model = eventDetailModel()
                            model.title = "Accepted".localized() + "(" + count + ")"
                            model.type = "going";
                            model.array = going
                            
                            for str in going {
                                
                                if(str == EMClient.shared().currentUsername )
                                {
                                    weakSelf?.hiddenFlag = 1
                                    break
                                }
                            }
                            
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }
                        else
                        {
                            let model = eventDetailModel()
                            model.title = "Accepted".localized() + "(0)"
                            model.type = "going";
                            model.array = []
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }
                        if let unread = loopE["unread"] as? [String] {
                            
//                            let tmp = weakSelf?.getEventArray(eventStr: unread)
                            let count = String(format: "%d", unread.count)
                            let model = eventDetailModel()
                            model.title = "Unread".localized() + "(" + count + ")"
                            model.type = "unread";
                            model.array = unread
                            for str in unread{
                                
                                if(str == EMClient.shared().currentUsername )
                                {
                                    weakSelf?.hiddenFlag = 2
                                    break
                                }
                            }
                            
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }
                        else
                        {
                            let model = eventDetailModel()
                            model.title = "Unread".localized() + "(0)"
                            model.type = "unread";
                            model.array = []
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }

                        if let notgoing  = loopE["notgoing"] as? [String] {
//                            let tmp = weakSelf?.getEventArray(eventStr: notgoing)
                            let count = String(format: "%d", notgoing.count)
                            let model = eventDetailModel()
                            model.title = "Canceled".localized() + "(" + count + ")"
                            model.type = "notgoing";
                            model.array = notgoing
                            
                            for str in notgoing{
                                
                                if(str == EMClient.shared().currentUsername )
                                {
                                    weakSelf?.hiddenFlag = 3
                                    break
                                }
                            }
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }
                        else
                        {
                            let model = eventDetailModel()
                            model.title = "Canceled".localized() + "(0)"
                            model.type = "notgoing";
                            model.array = []
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }
                        
                        // MARK:评论
                        if let comments  = loopE["comments"] as? [Any] {
                            //                            let tmp = weakSelf?.getEventArray(eventStr: notgoing)
                            let count = String(format: "%d", comments.count)
                            let model = eventDetailModel()
                            model.title = "Comment".localized() + "(" + count + ")"
                            model.type = "evaluate";
                            
                            var array = [evaluateModel]()
                            
                            
                            for obj in comments{
                                
                                var tmp = obj as! [String:String]
                                let eModel = evaluateModel()
                                eModel.username = tmp["username"] as! String
                                eModel.timestatmp = weakSelf?.intervalSinceNow(dateStr: tmp["timestatmp"] as! String)
                                eModel.comment = tmp["comment"] as! String
                                array.append(eModel)
                            }
                            
//                            model.array = unread
                            
//                            guard let 
                            model.evaluateArr = array
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }
                        else
                        {
                            let model = eventDetailModel()
                            model.title = "Comment".localized() + "(0)"
                            model.type = "evaluate";
                            model.evaluateArr = []
                            weakSelf?.dataDic[weakSelf!.dataDic.count] = model
                        }
                        

                        weakSelf?.commentBtn.isHidden = false
                        if(EMClient.shared().currentUsername != owner as? String)
                        {
//                            weakSelf?.hiddenFlag = 0
                            if weakSelf?.hiddenFlag != -1
                            {
                                weakSelf?.acceptBtn.isHidden =  false
                                weakSelf?.cancelBtn.isHidden = false
                            }
                        }
                        if(weakSelf?.hiddenFlag == 1)
                        {
                            weakSelf?.acceptBtn.backgroundColor = UIColor.lightGray
                            weakSelf?.acceptBtn.isEnabled = false
                        }
                        else if(weakSelf?.hiddenFlag == 2)
                        {
//                            weakSelf?.acceptBtn.backgroundColor = UIColor.lightGray
//                            weakSelf?.acceptBtn.isEnabled = false
                        }
                        else if(weakSelf?.hiddenFlag == 3)
                        {
                            //weakSelf?.acceptBtn.backgroundColor = UIColor.lightGray
                            weakSelf?.acceptBtn.isEnabled = true
                            weakSelf?.cancelBtn.backgroundColor = UIColor.lightGray
                            weakSelf?.cancelBtn.isEnabled = false
                        }
                        
                        if let images   = loopE["images"] as? [String]
                        {
                            
                            for obj in images{
                               
                                weakSelf?.imageList.append(CUHTTP.URL.ROOT.dropLast() +  String(describing: obj).trimmingCharacters(in: .whitespaces))
                                
                                weakSelf?.view.setNeedsUpdateConstraints()
                            }
                         
                        }
                        
                        weakSelf?.stopAnimating()
                        weakSelf?.collectionView.reloadData()
                        
                    }
                }
            }
            
        },
        failure:{ response in
                print(response ?? " ")
                weakSelf?.show(response ?? " ")
        })
    }
    
//    private func getEventArray(eventStr:String)->[String]{
//         var  string = eventStr.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: " ", with: "")
//        let array = string.split(separator: ",")
//
//        var strArr = [String]()
//        for item in array {
//            let start = item.index(item.startIndex, offsetBy: 2)
//            let end = item.index(item.endIndex, offsetBy: -1)
//            let result = item[start..<end]
//            let str = String(result)
//            strArr.append(String(describing: str).trimmingCharacters(in: .whitespaces))
//        }
//
//        print("array = ",array)
//
//        return strArr
//    }
    
//    private func getImageArray(imgStr:String){
//
////        for i in 0..<imageList.count {
//
////            var imageStr = imageList[i]
//        var  string = imgStr.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: " ", with: "")
//        let array = string.split(separator: ",")
//
//        var strArr = [String]()
//        for item in array {
//            let start = item.index(item.startIndex, offsetBy: 3)
//            let end = item.index(item.endIndex, offsetBy: -1)
//            let result = item[start..<end]
//            let str =  String(result)
//
//    imageList.append(CUHTTP.URL.ROOT +  String(describing: str).trimmingCharacters(in: .whitespaces))
////                strArr.append(String(describing: str).trimmingCharacters(in: .whitespaces))
//        }
//    }

    
    func postEventStatus(status:String) {

        let cuHTTP = CUHTTP.instance()

        let urlstr = "eventStatus"

        var parameters: [String: Any]
        
        let owner = EMClient.shared().currentUsername ?? ""

        parameters = [
            "eventId" : eid,
            "status" : status,
            "guest" : owner,
        ]

        print(parameters)
        
        weak var weakSelf = self

        cuHTTP.makePostData(url: urlstr, parameters: parameters,
                            success: {response in
                                print(response?.response?.statusCode ?? "??")      //成功时，返回200
                                
                                if let code = response?.response?.statusCode  {
                                    if(code == 200)
                                    {
                                        weakSelf?.show("Succeed".localized())
                                        weakSelf?.navigationController?.popViewController(animated: true)
                                    }
                                }

                            } ,
                            failure: {response in
                            
                            }
        )

    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.dataDic.keys.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let model:eventDetailModel = (dataDic[section] ?? nil)!
        if(section == 3)
        {
            return model.evaluateArr?.count ?? 0
        }
        else
        {
            return model.array?.count ?? 0
        }
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
//        print("indexPath111 = \(indexPath)");
        
        if indexPath[0] == 3
        {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "evaluateListCell", for: indexPath) as! EvaluateListCell

            let model:eventDetailModel = (dataDic[indexPath.section] ?? nil)!
            let eModel = model.evaluateArr?[indexPath.row]
            cell.refreshCell(model: eModel!)
            return cell
        }
        else
        {
 
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! EventDetailCollCell
            let model:eventDetailModel = (dataDic[indexPath.section] ?? nil)!
            let name = model.array?[indexPath.row]
            cell.refreshCell(name: name ?? "")
            return cell
        }
        

    }
    
    //
    //这个是设定header和footer的方法，根据kind不同进行不同的判断即可
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        
        let resuableView = collectionView.dequeueReusableSupplementaryView(ofKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "header", for: indexPath) as! CollectionReusableView
        
//        resuableView.backgroundColor = UIColor.white
        
        let model:eventDetailModel = (dataDic[indexPath.section] ?? nil)!
        
        
        
        resuableView.nameLabel.text = model.title
        return resuableView
    }
    //header高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: UIScreen.main.bounds.size.width, height: 55)
    }
    
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
     {
        return 20
     }
    
   
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {
        return 20
    }
    
    /**
     可以定制不同的item
     return： item的大小
     */
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{

//        print("indexPath = \(indexPath)")

//        let tmpIndexPath = self.collectionView.indexPath(for: <#T##UICollectionViewCell#>)


        if indexPath[0] == 3
        {

            return CGSize(width:kScreenWidth, height: 80)
        }
        else
        {
            let screenWidth:Int = Int(UIScreen.main.bounds.width)

            let width = (screenWidth - 6 * 20 ) / 5

            let itemSize = CGSize(width: width, height: width + 35)

            return itemSize
        }
    }
    
    
    // 获取日期差，yyyy-MM-dd HH:mm:ss格式
    
    func intervalSinceNow(dateStr:String) -> String{
        
        let format = DateFormatter.init()
        
        format.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let tmpStr = dateStr.split(separator: ".")[0]
        
        let date = format.date(from: String(tmpStr))
        
        
        let fromZone = TimeZone.current
        
        let fromInterval = fromZone.secondsFromGMT(for: date!)
        
        let fromDate = date?.addingTimeInterval(Double(fromInterval))
        
        
        
        let adate = Date()
        
//        let zone = TimeZone.current
//
//        let interval = zone.secondsFromGMT(for: adate)
//
//        let localeDate = adate.addingTimeInterval(Double(interval))
        
   
        
        let interValTime = fromDate!.timeIntervalSinceReferenceDate - adate.timeIntervalSinceReferenceDate
        
        let lTime = fabs(interValTime)
        
        
        let iMinutes = (Int((lTime / 60))) + 1
        
        let iHours = Int(lTime / 3600)
        
        let iDays: Int = Int(lTime / 60 / 60 / 24);
        
        //    let iMonth = Int(lTime / 60 / 60 / 24 / 12);
        
        //    let iYears = Int(lTime / 60 / 60 / 24 / 384);
        
        var timeString = ""
        
        if (iDays >= 1)
        {
            timeString = String.init(describing:iDays) + "day(s) ago".localized()
        }
        else if(iMinutes >= 60 && iHours < 24)
        {
            timeString = String.init(describing:iHours) + "hour(s) ago".localized()
        }
            
        else
        {
            timeString = String.init(describing:iMinutes) + "min(s) ago".localized()
        }
  
        return timeString
        
    }
}



